import json
import logging
import re
import time

SUBREDDIT_NAME = 'Piracy'
console_logger = logging.getLogger('console_logger')

class Linker:
    keywords_url = 'https://www.reddit.com/r/Piracy/wiki/keywords_json'
    keywords_json_file = 'settings/WikiLinker_keywords.json'
    cache_frequency_secs = 5 * 60
    max_matches = 3

    def __init__(self, reddit):
        self.subreddit = reddit.subreddit(SUBREDDIT_NAME)
        self.last_cached = 0
        self.keywords = None
        self._load_keywords()

    def handle_comment(self, comment):
        if comment.subreddit.display_name != SUBREDDIT_NAME:
            return

        self._load_keywords()

        kw_matches = self._get_kw_matches(comment)
        if kw_matches:
            self._send_reply(comment, kw_matches)


    def _get_kw_matches(self, comment):
        kw_matches = []
        for keyword in self.keywords:
            keyword_re = fr'!{keyword}\b'

            if re.search(keyword_re, comment.body, re.IGNORECASE):
                kw_matches.append(keyword)
            if len(kw_matches) >= self.max_matches:
                break
        return kw_matches


    def _send_reply(self, comment, kw_matches):
            console_logger.info(f" Replying to keyword(s)")
            reply_body = 'Here are your link(s)!\n\n'

            for i, kw in enumerate(kw_matches):
                wiki_name = self.keywords[kw][0]
                wiki_url = self.keywords[kw][1]

                reply_body += f'{i + 1}. Link to [{wiki_name}]({wiki_url})\n\n'

            reply_body += f'&nbsp;\n\n---\n\n^^^^I ^^^^am ^^^^a ^^^^Bot. ^^^^Here ^^^^is ^^^^a [^^^^list ^^^^of ^^^^keywords.]({self.keywords_url})'
            myreply = comment.reply(reply_body)
            myreply.disable_inbox_replies()

    def _load_keywords(self):
        if time.time() - self.last_cached > self.cache_frequency_secs:
            with open(self.keywords_json_file, 'r', encoding='utf8') as f:
                self.keywords = json.load(f)
            self.last_cached = time.time()
